#!/usr/bin/python
# -*- coding: utf-8 -*-

import re
import traceback
import logging
from datetime import datetime
import cgi

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.api import mail


from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write(self.reqContent(urlfetch.GET))
        
    def post(self):
        self.response.out.write(self.reqContent(urlfetch.POST))
        
    def reqContent(self, method=urlfetch.GET):
        logging.info('*'*60)
        
        data = None
        if method == urlfetch.POST:
            data = self.request.body

        host = "http://www.newsmth.net"
        url = ""
        req_full_path = self.request.url
        req_full_path = req_full_path[req_full_path.find('/a/'):]
        if req_full_path=='/a/' or req_full_path.startswith('/a/?'):
            req_full_path = req_full_path[req_full_path.find('?'):]
            url = host + "/atomic2.php" + req_full_path
        else:
            req_full_path = req_full_path[req_full_path.find('/', 1):]
            url = host + req_full_path
        
        htmlcontent = ""
        headers, htmlcontent = self.httpRequest(url, method, data)
        #logging.info(htmlcontent)

        htmlcontent = htmlcontent.replace("href='/att.php", "href='"+host+"/att.php")
        
        cssContent = self.getUserStyle()
        if cssContent:
            cssContent = cssContent.encode('ascii','ignore')
        
        htmlcontent = htmlcontent.replace('</head>', '<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"><script src="/media/atomic/pda.js" type="text/javascript"></script>\n<style>\n'+cssContent+'\n</style>\n</head>')

        #self.response.headers['Content-Type'] = headers['Content-Type']
        #logging.info(headers['Content-Type'])
        js = '''
        <script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-4049556-4");
pageTracker._trackPageview();
</script>
        '''
        htmlcontent = htmlcontent.replace('</body>', js+'</body>')
        return htmlcontent
        
    def httpRequest(self, url, method=urlfetch.GET, data=None):
        count = 1;
        while(count < 3):
            response = None
            try:
                #urlfetch.REDIRECT_STATUSES = frozenset([httplib.SEE_OTHER])
                response = urlfetch.fetch(url=url, follow_redirects=False, method=method, payload=data)
                
                redirect_counts = 0
                while redirect_counts < 5 and response and response.status_code in [301,302]:
                    logging.info(str(count)+"--"+url+", status_code:"+str(response.status_code))
                    if response.headers.has_key('location'):
                        url = response.headers['location']
                    elif response.headers.has_key('Location'):
                        url = response.headers['Location']
                    else:
                        raise Exception('Could not find location in headers: %r' % (response.headers,))
                    smthhost = "http://www.newsmth.net"
                    url = smthhost + '/' +url
                    #logging.info("new url:"+url)
                    response = urlfetch.fetch(url=url, follow_redirects=False)
                    redirect_counts += 1

            except:
                logging.info(traceback.format_exc())
                count = count + 1
                continue
            logging.info(str(count)+"--"+url+", status_code:"+str(response.status_code))
            if response and response.status_code==200:
                return response.headers, self.converFromGB2312ToUTF8(response.content)
            else:
                count = count + 1
    
    def converFromGB2312ToUTF8(self, onestr):
        newstr = onestr
        try:
            newstr = unicode(newstr, 'cp936', 'ignore')
        except:
            pass
        return newstr.encode('utf-8', 'ignore')
        
    def getUserStyle(self):
        user = users.get_current_user()
        if not user:
            user = users.User('anonymous@gmail.com')
        userStyle = db.GqlQuery("SELECT * FROM UserStyle WHERE user=:1", user).get()
        if userStyle:
            return userStyle.cssContent
        else:
            return ""

class UserStyle(db.Model):
    user = db.UserProperty()
    cssContent = db.TextProperty()
    created_on = db.DateTimeProperty(auto_now_add = True)
    last_update = db.DateTimeProperty(auto_now = True)


class Config(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if not user:
            self.response.set_status(302)
            url = users.create_login_url(self.request.url)
            self.response.headers['Location'] = url
        
        
        self.response.out.write('<html><body><form method="POST" action="/a/config/">')
        defaultCss = '''
body {
    padding: 0px;
    margin: 0px;
    font-family: Tahoma, Georgia, Verdana, hei;
    font-size: 16px;
    -webkit-text-size-adjust: none;
    /*
    -webkit-user-select: none;
    */
    background-color: #222;
    COLOR: #CCCCCC;
    line-height: 1.5;
}

body[orient="profile"] .line2{
    height: 436px;
}

body[orient="landscape"] .line2{
    height: 258px;
}


.ctt { }

.bg1 {}
.bg2 {text-align:center; }

.bg3 {line-height:200%;}
A.bg3:link {COLOR: #ffffff;}
A.bg3:visited {color:#f0f0f0;}
A.bg3:active {color:#ffffff;}
A.bg3:hover {color:#ffffff;text-decoration: underline;}

.line1 {}
.line2 {width: 100%;}
.bgf {text-align:center; }
.tab { border:1px solid #3C3C78; text-align:center;}
.td_t { border-bottom:1px solid #CDCDD7; }
.td_b { border-top:1px solid #CDCDD7; }
.top5 {margin-top:5px;}
.test {border:1px solid #F00;}
td {font-size: 16px;}
th {font-size: 16px;}


a {text-decoration: none;}
a:link {color: #CAFF70;}
A:visited {color: #336600;}
A:hover {text-decoration: underline;color: red;}
'''
        userStyle = db.GqlQuery("SELECT * FROM UserStyle WHERE user=:1", user).get()
        if userStyle:
            defaultCss = userStyle.cssContent.encode('ascii','ignore')
            
        self.response.out.write('pda.css:<br/><textarea name="css" style="width:400px;height:600px;">'+defaultCss+'</textarea><br/><input type="submit" value="submit">')
        self.response.out.write(cgi.escape(self.request.get('content')))
        self.response.out.write('</form></body></html>')

    def post(self):
        user = users.get_current_user()
        if not user:
            self.response.set_status(302)
            url = users.create_login_url(self.request.url)
            self.response.headers['Location'] = url
        
        cssContent = self.request.get('css')
        
        userStyle = db.GqlQuery("SELECT * FROM UserStyle WHERE user=:1", user).get()
        if userStyle:
            userStyle.cssContent = cssContent
        else:
            userStyle = UserStyle(user=user, cssContent=cssContent)
        userStyle.put()
        
        self.response.out.write("<h1><a href='/a/'>home</a></h1>")
        self.response.out.write("<h1><a href='"+users.create_logout_url(self.request.url)+"'>Logout</a></h1>")
        self.response.out.write("<pre>"+cgi.escape(self.request.get('css'))+"</pre>")
    
def main():
    application = webapp.WSGIApplication([('/a/config.*', Config), ('/a/.*', MainPage)], debug=True)
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

    
    
# ##########################################################################################################################
# /


